package com.wcs.exam.dao.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wcs.exam.controller.admin.resp.AdminStatLogin;
import com.wcs.exam.dao.UsersLogDao;
import com.wcs.exam.dao.impl.mapper.UsersLogMapper;
import com.wcs.exam.dao.impl.mapper.entity.UsersLog;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户注册登录日志 持久化实现类
 *
 * @author wcs
 * @since 2025-03-26
 */
@Repository
public class UsersLogDaoImpl extends ServiceImpl<UsersLogMapper, UsersLog> implements UsersLogDao {

    @Override
    public <R> List<R> selectObjs(Wrapper<UsersLog> wrapper, Class<R> classType) {
        List<Map<String, Object>> resultMaps = baseMapper.selectMaps(wrapper);
        if (CollectionUtil.isEmpty(resultMaps)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(resultMaps, classType);
    }

    @Override
    public List<AdminStatLogin> statByDate(Integer dates) {
        QueryWrapper<UsersLog> wrapper = new QueryWrapper<>();
        wrapper.select("DATE_FORMAT(gmt_create, '%Y-%m-%d') as dates, count(*) as logins, login_status");
        wrapper.gt("login_status", 0).gt("gmt_create", DateUtil.offsetDay(new Date(), dates));
        wrapper.groupBy("dates,login_status");
        wrapper.orderByAsc("dates");
        return selectObjs(wrapper, AdminStatLogin.class);
    }
}
